#include <iostream>
#include <pthread.h>
#include <string>
#include <cstring>
#include <unistd.h>

void *routine(void *args)
{
    std::string name = (char *)args;
    while (true)
    {
        sleep(1);
        std::cout << "I am a thread, name: " << name << std::endl;
    }

    return (void *)123;
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, routine, (void *)"thread-1");

    // 分离新线程
    pthread_detach(tid);

    sleep(10);
    // 取消新线程
    pthread_cancel(tid);

    // 等待新线程，获取返回值
    void *retval = nullptr;
    int ret = pthread_join(tid, &retval);
    if (ret != 0)
        std::cout << "等待失败，" << strerror(ret) << std::endl;
    else
        std::cout << "等待成功" << std::endl;

    while (true)
    {
        std::cout << "当前是主线程，新线程已被回收，退出信息为：" << (long long int)retval << std::endl;
        sleep(1);
    }

    return 0;
}